//
//  PicturesView.swift
//  weibo
//
//  Created by tomato on 2023/9/28.
//

import UIKit
import Kingfisher


class PicturesView: UIView {
    /** 列数  */
    var colums:Int = 3
    /** 左边间距  */
    var leftMargin:CGFloat = 0.0
    /** 右边间距  */
    var rightMargin:CGFloat = 0.0
    /** 上边间距  */
    var topMargin:CGFloat = 0.0
    /** 底部边间距  */
    var bottomMargin:CGFloat = 0.0
    /** colums(每一列之间的间距)间距  */
    var columsMargin:CGFloat = 0.0
    /** row(每一行之间的间距)间距  */
    var rowMargin:CGFloat = 0.0
     /** 单元View的高度  */
    var unitViewHeight:CGFloat = 50.0
    /**  数据源  */
    var pictureArray:[String]? {
        didSet {
            //移除所有的子view
            subviews.forEach {
                $0.removeFromSuperview()
            }
            self.addSubViews(picturesArray:pictureArray!)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func addSubViews(picturesArray:[String]){
        for urlStr in pictureArray! {
            
            let imageView = UIImageView()
            imageView.set_Image(image: urlStr)
            self.addSubview(imageView)
            
            let itemW = (self.bounds.size.width - self.leftMargin - self.rightMargin - (self.colums - 1).wd_CGFloat * self.columsMargin) / (self.colums.wd_CGFloat)
            let itemH = self.unitViewHeight
            var row = 0,colum = 0
            for i in 0...pictureArray!.count - 1 {
                row = i / self.colums
                colum = i % self.colums
                imageView.snp.makeConstraints { (make) in
                    make.leading.equalTo(self).offset((self.leftMargin + (self.columsMargin + itemW) * colum.wd_CGFloat))
                    make.top.equalTo(self).offset((self.topMargin + (itemH + self.rowMargin)*row.wd_CGFloat ))
                    make.width.equalTo(itemW)
                    make.height.equalTo(itemH)
                    if i == pictureArray!.count - 1 {
                        make.bottom.equalTo(self.snp.bottom).offset(0)
                    }
                }

            }
            
        }
    }
}


